package com.atzongmaotan.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName:    BIOServerSocket
 * Package:  com.atzongmaotan
 * Description:
 *          telnet 127.0.0.1 6666
 *          send message信息
 *          大量线程,处理连接
 *          建立连接,没有数据读取时,发生阻塞
 * @Author: interface
 * @Create: 2024/9/29 - 上午12:42
 * @Version: v1.0
 */
public class BIOServerSocket {
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动~~~~~~");
        while(true){
            System.out.println("等待连接~~~~");
            Socket socket = serverSocket.accept();
            //连接到客户端
            executorService.execute(new Runnable() {
                public void run() {
                    handler(socket);
                }
            });
        }
    }
    public static void handler(Socket socket) {
        try {
            System.out.println("线程ID : " + Thread.currentThread().getId()+"线程Name:="+Thread.currentThread().getName());
            byte[] buffer = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true) {
                System.out.println("线程ID : " + Thread.currentThread().getId()+"线程Name:="+Thread.currentThread().getName());
                System.out.println("等待读取~~~~");
                int read = inputStream.read(buffer);
                if (read != -1) {
                    //输出客户端发送来的数据
                    System.out.println(new String(buffer, 0, read));
                }else {
                    break;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
